/**
 * @description 处理echarts可能需要用到的公共方法
 * @author gf
 *
 *
 */
import dayjs from "dayjs";
import * as _ from "lodash";
import * as echarts from "echarts";
export const TOOLTIP_FONT_SIZE = 12; // 全局图表hover默认样式

export const AxisArr = ["左轴", "右轴"];

/**基础十色**/
export const getBaseColors = (opacity: number | string = 1) => {
  return [
    `rgba(52, 87, 196,${opacity})`,
    `rgba(116, 130, 149,${opacity})`,
    `rgba(64, 166, 223,${opacity})`,
    `rgba(23, 167, 133,${opacity})`,
    `rgba(232, 92, 54,${opacity})`,
    `rgba(253, 192, 113,${opacity})`,
    `rgba(141, 177, 152,${opacity})`,
    `rgba(161, 101, 76, ${opacity})`,
    `rgba(134, 76, 161, ${opacity})`,
    `rgba(164, 178, 196, ${opacity})`,
  ];
};

/**补充色**/
export const getExpandColors = (opacity: number | string = 1) => {
  return [
    `rgba(37, 163, 194, ${opacity})`,
    `rgba(103, 77, 160, ${opacity})`,
    `rgba(253, 211, 4, ${opacity})`,
    `rgba(185, 130, 73, ${opacity})`,
    `rgba(137, 48, 29, ${opacity})`,
    `rgba(198, 134, 135, ${opacity})`,
    `rgba(159, 207, 95, ${opacity})`,
    `rgba(0, 121, 68, ${opacity})`,
    `rgba(34, 50, 115, ${opacity})`,
    `rgba(173, 29, 29, ${opacity})`,
    `rgba(80, 120, 247, ${opacity})`,
    `rgba(159, 182, 214, ${opacity})`,
    `rgba(102, 200, 255, ${opacity})`,
    `rgba(18, 207, 162, ${opacity})`,
    `rgba(255, 147, 117, ${opacity})`,
    `rgba(255, 217, 167, ${opacity})`,
    `rgba(179, 231, 195, ${opacity})`,
    `rgba(222, 140, 105, ${opacity})`,
    `rgba(190, 102, 231, ${opacity})`,
    `rgba(239, 171, 191, ${opacity})`,
    `rgba(235, 156, 61, ${opacity})`,
  ];
};

/**
 *
 * @param params 图表数据源
 * @param string 需要特别处理的展示字段，主要是百分号,传入对应的legend
 * @returns
 */
export const formatterTooltip = (params: any, string?: string[]) => {
  let str = "";
  let title = "";
  params.forEach((v) => {
    const { marker, seriesName, value, axisValue } = v;
    title = axisValue;
    const val = value[1];

    const a =
      val !== undefined && val !== null
        ? `${marker + seriesName}&nbsp;` +
          (string && string?.indexOf(seriesName) > -1
            ? `${val?.toFixed(2)}%`
            : val?.toFixed(2)) +
          `<br />`
        : "";
    str += a;
  });
  return `${title}<br />${str}`;
};

export const toopTipStyle = (params?: any) => {
  return {
    trigger: "axis",
    backgroundColor: "rgba(0,0,0,0.75)",
    borderWidth: 0,
    textStyle: {
      fontSize: TOOLTIP_FONT_SIZE,
      color: "#fff",
    },
  };
};

export const axisLineStyle = (params?: any) => {
  return {
    lineStyle: {
      color: "#EDF0F5",
      width: 1,
      type: "solid",
    },
  };
};

export const axisLabelStyle = (params?: any) => {
  return {
    color: "rgba(53, 66, 94, 0.7)",
    fontSize: 10,
    align: "center",
    margin: 16,
  };
};

export const yaxisLineStyle = (params?: any) => {
  return {
    show: true,
    lineStyle: {
      type: "dashed",
      color: "#EDF0F5",
    },
  };
};

/**
 *
 * @param params y轴数据单位
 * @param precision 保留精度位数
 * @returns y轴文本展示配置
 */

export const yaxisLabelStyle = (params?: any, precision?: number = 1) => {
  return {
    color: "rgba(53, 66, 94, 0.7)",
    fontSize: 10,
    inside: true,
    margin: 8,
    verticalAlign: "bottom",
    formatter: (value, index) => {
      return params ? `${value.toFixed(precision)} ${params}` : value;
    },
  };
};

export const splitLineStyle = (params?: any) => {
  return {
    splitLine: {
      show: true,
      lineStyle: {
        type: "dashed",
        color: "#EDF0F5",
      },
      ...params,
    },
  };
};

// 对后端返回的连续日期类的折线图进行排序，防止绘制错误
export const sortLineData = (data: any) => {
  if (!_.isArray(data)) return [];
  data.map((v) => {
    v.value.sort((a: any, b: any) => (dayjs(a.key) > dayjs(b.key) ? 1 : -1));
  });

  return data;
};

// 导出图片
export const downloadImg = (title: string, options) => {
  const largerDom = document.createElement("div");
  largerDom.style.position = "absolute";
  largerDom.style.top = 0;
  largerDom.id = "download_enlarge_chart";
  largerDom.style.display = "block";
  largerDom.style.width = "1200px";
  largerDom.style.height = "600px";
  largerDom.style.display = "none";
  const isExist = document.getElementById("download_enlarge_chart");
  if (isExist) {
    document.body.removeChild(isExist);
  }
  document.body.appendChild(largerDom);
  const echartsInstance2 = echarts.init(largerDom);
  echartsInstance2.setOption(options);

  setTimeout(() => {
    const base64Url = echartsInstance2?.getDataURL({
      pixelRatio: 2,
      backgroundColor: "#fff",
    });
    // const a = document.createElement('a')
    // a.href=base64Url
    // a.setAttribute('download', title)
    // a.click()
    // return
    const img = new Image();
    img.src = base64Url;
    img.onload = () => {
      const canvas = document.createElement("canvas");
      canvas.width = img.width;
      canvas.height = img.height;
      const ctx = canvas.getContext("2d");
      ctx.drawImage(img, 0, 0);
      const dataURL = canvas.toDataURL("image/png");

      const a = document.createElement("a");
      // 创建一个单击事件
      const event = new MouseEvent("click");
      // 将a的download属性设置为我们想要下载的图片名称，若name不存在则使用‘下载图片名称’作为默认名称
      if (title.indexOf(".") > -1) {
        a.download = title + ".png";
      } else {
        a.download = title;
      }
      // 将生成的URL设置为a.href属性
      a.href = dataURL;
      a.dispatchEvent(event);
    };
  }, 1000);
};

//返回事件对应的echarts类型
export const getEchartsTypes = (eventCode: string): string => {
  const getArrFromCode = (arr: Array<string>, type: string) => {
    let codeObj = {};
    arr.forEach((item: string) => (codeObj[item] = type));
    return codeObj;
  };
  //多折线图
  const multiplue_line_arr = [
    "fund_profit_potential", //货基收益提醒
    "fund_profit_risk1", //货基风险提醒一
    "fund_profit_risk2", //货基风险提醒二
  ];

  //折线带点图-峰值
  const line_and_dot_arr = [
    "fund_profit_release", //货基收益释放提醒
  ];

  //堆积图
  const area_arr = [
    "heavy_holding_industry_alert_sw", //重仓行业变化（申万）,
    "stock_holding_alert_report", //股票仓位变化（基于定报）,
    "heavy_holding_industry_alert_zz", //重仓行业变化（中证）
    "heavy_holding_industry_alert_quarterly", //重仓行业变化（季度披露）
    "heavy_holding_industry_alert_predicted", //重仓行业变化（预测）
    "stock_holding_alert_predicted", //股票仓位变化(预测)
  ];
  //柱状折线图+折线图双图
  const line_and_bar_arr = [
    "duration_alert_interestrate", //久期异常（利率风险）
    "duration_alert_predicted", //久期异常（净值拟合）
  ];
  //折线图中间带柱状区域
  const line_and_area_arr = [
    "deviation_from_benchmark_index_negative", //与业绩基准负偏移
    "deviation_from_benchmark_index_positive", //与业绩基准正偏移
    "deviation_from_benchmark_fundtype_negative", //与同类型负偏移
    "deviation_from_benchmark_fundtype_positive", //与同类型正偏移
    "deviation_from_benchmark_style_negative", //与风格指数负偏移
    "deviation_from_benchmark_style_positive", //与风格指数正偏移
    "maxdrawback_alert", //最大回撤超越历史
  ];

  const line_arr = [
    "", //重仓行业变化（申万）,
  ];
  const pie_arr = [
    "", //重仓行业变化（申万）,
  ];
  const bar_arr = [
    "stock_factor_alert", //因子重大变化,
  ];

  const three_table_arr = [
    "trade_condition_alert_status", //申赎状态变化
    "trade_condition_alert_limit", //单日限额提醒
  ];
  //普通表格
  const table_arr = [
    "fund_manager_change", //基金经理变更，
  ];
  const special_table_arr = [
    "credit_alert", //信用异常
    "stock_consensus_alert", //股票一致性预期变化
    "bond_deviate_valuation_negative_change", // 债券价格负偏离
    "bond_deviate_valuation_positive_change", // "债券价格正偏离"
  ];

  const special_table_arr2 = [
    "bond_deviate_valuation_negative_change", // 债券价格负偏离
    "bond_deviate_valuation_positive_change", // "债券价格正偏离"
  ];

  //合并表格
  const add_table_arr = [
    "dividend_alert", //基金分红
  ];
  let total_flect = {
    ...getArrFromCode(area_arr, "area"),
    ...getArrFromCode(table_arr, "table"),
    ...getArrFromCode(special_table_arr, "special_table"),
    ...getArrFromCode(line_and_bar_arr, "line_and_bar"),
    ...getArrFromCode(line_and_area_arr, "line_and_area"),
    ...getArrFromCode(three_table_arr, "three_table"),
    ...getArrFromCode(add_table_arr, "add_table"),
    ...getArrFromCode(bar_arr, "bar"),
    ...getArrFromCode(multiplue_line_arr, "multiplue_line"),
    ...getArrFromCode(line_and_dot_arr, "line_and_dot"),
    ...getArrFromCode(special_table_arr2, "special_table2"),
  };

  return total_flect[eventCode];
};
